//
//  UserInfoController.m
//  CharlesMVX
//
//  Created by Charles on 2020/3/11.
//  Copyright © 2020 Charles. All rights reserved.
//

#import "MVCUserInfoController.h"
#import "User.h"
#import "UIView+Controller.h"
#import "UserInfoView.h"
#import "UserAPIManager.h"

@interface MVCUserInfoController ()

@property (copy, nonatomic) ViewControllerGenerator VCGenerator;
@property (strong, nonatomic) User *user;
@property (assign, nonatomic) NSUInteger userId;
@property (nonatomic, strong) UserInfoView *userInfoView;
@property (nonatomic, strong) UINavigationController *navCtrl;
@end

@implementation MVCUserInfoController

+ (instancetype)instanceWithUserId:(NSUInteger)userId {
    MVCUserInfoController *controller = [[MVCUserInfoController alloc]initWithUserId:userId];
    return controller;
}

- (instancetype)initWithUserId:(NSUInteger)userId {
    if (self = [super init]) {
        self.userId = userId;
        self.userInfoView = [[UserInfoView alloc]init];
        [self.userInfoView addTarget:self selector:@selector(clickEvent)];
    }
    return self;
}

- (UserInfoView *)userInfoView {
    return _userInfoView;
}

- (void)setNavigationController:(UINavigationController *)navCtrl {
    self.navCtrl = navCtrl;
}

- (void)fetchData {
    [[UserAPIManager new] fetchUserInfoWithUserId:self.userId completionHandler:^(NSError *error, id result) {
        if (error) {
            //            ... show error view in userInfoView
        } else {
            User *user = self.user = result;
            [self.userInfoView setName:user.name];
            [self.userInfoView setBlogCnt:[NSString stringWithFormat:@"作品：%@",@(user.blogCount)]];
            [self.userInfoView setFriendsCnt:[NSString stringWithFormat:@"好友：%@",@(user.friendCount)]];
            [self.userInfoView setSummary:[NSString stringWithFormat:@"个人简介：%@",@(user.blogCount)]];
            [self.userInfoView setHeadImage:[UIImage imageNamed:user.icon]];
        }
    }];
}

- (void)clickEvent {
    if (self.VCGenerator) {
        UIViewController *targetVC = self.VCGenerator(self.user);
        [self.navCtrl pushViewController:targetVC animated:YES];
    }
}

@end
